const express = require('express')
//引入权限控制模块
const isLoginMiddle = require('../middleware/isLoginMiddle')

//引入数据库
const advModel = require('../db/model/advModel')
const path = require('path')

//创建一个路由
const route = express.Router();

//引入formidableFormData格式的解析器
const formidable = require('formidable')

route.post('/addAdv', isLoginMiddle, async (req, res) => {   //这个位置的路径不需要加api1
  const form = formidable({
    uploadDir: path.resolve(__dirname, '../upload'),
    keepExtensions: true
  })
  form.parse(req, async (err, params, file) => {
    const {
      advTitle, advType, advOrder
    } = params
    //向数据库添加数据
    try {
      await advModel.create({
        advTitle,
        advType,
        advOrder,
        advHref: '/upload/' + file.advPic.newFilename,
        addTime: new Date().toLocaleString()
      })
      return res.send({
        code: 10000,
        msg: '添加广告成功',
        data:null
      })
    } catch (e) {
      console.log('添加广告数据库操作出现异常' + e.message);
      return res.send({
        code: 10000,
        msg: '添加广告数据库操作出现异常' + e.message,
        data:null
      })
    }
  })


})

module.exports = route